{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9HcmLuWtE213"
      },
      "source": [
        "# Magenta RT: Streaming music generation!\n",
        "\n",
        "<a href=\"https://colab.research.google.com/github/magenta/magenta-realtime/blob/main/notebooks/Magenta_RT_Demo.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
        "\n",
        "Magenta RealTime is a Python library for streaming music audio generation on\n",
        "your local device. It is the open weights / on device companion to\n",
        "[MusicFX DJ Mode](https://labs.google/fx/tools/music-fx-dj) and the\n",
        "[Lyria RealTime API](https://ai.google.dev/gemini-api/docs/music-generation).\n",
        "\n",
        "-   [Blog Post](https://g.co/magenta/rt)\n",
        "-   [Repository](https://github.com/magenta/magenta-realtime)\n",
        "-   [HuggingFace](https://huggingface.co/google/magenta-realtime)\n",
        "\n",
        "### Generating audio with Magenta RT\n",
        "\n",
        "Magenta RT generates audio in short chunks (2s) given a finite amount of past\n",
        "context (10s). We use crossfading to mitigate boundary artifacts between chunks.\n",
        "More details on our model are coming soon in a technical report!\n",
        "\n",
        "![Animation of chunk-by-chunk generation in Magenta RT](https://raw.githubusercontent.com/magenta/magenta-realtime/refs/heads/main/notebooks/diagram.gif)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1l6sF-r_lISR"
      },
      "source": [
        "# Step 1: 😴 One-time setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EZxgPBfi-bPf",
        "cellView": "form"
      },
      "outputs": [],
      "source": [
        "# @title **Run this cell** to install dependencies (~5 minutes)\n",
        "# @markdown Make sure you are running on **`v5e-1 TPU` runtime** via `Runtime > Change Runtime Type`\n",
        "\n",
        "# @markdown Colab may prompt you to restart session. **Wait until the cell finishes running to restart**!\n",
        "\n",
        "# Clone library\n",
        "!git clone https://github.com/magenta/magenta-realtime.git\n",
        "!git clone https://github.com/google-research/t5x.git\n",
        "\n",
        "# Install library and dependencies\n",
        "# If running on TPU (recommended, runs on free tier Colab TPUs):\n",
        "!pip install -e t5x/[tpu] && pip install -e magenta-realtime/[tpu] && pip install tf2jax==0.3.8\n",
        "\n",
        "# Uncomment if running on GPU (requires A100 via Colab Pro to be fast enough):\n",
        "# !patch t5x/setup.py < magenta-realtime/patch/t5x_setup.py.patch\n",
        "# !patch t5x/t5x/partitioning.py < magenta-realtime/patch/t5x_partitioning.py.patch\n",
        "# !pip install -e t5x/[gpu] && pip install -e magenta-realtime/[gpu] && pip install tf2jax==0.3.8\n",
        "\n",
        "!sed -i '/import tensorflow_text as tf_text/d' /usr/local/lib/python3.12/dist-packages/seqio/vocabularies.py\n",
        "!sed -i \"s|device_kind == 'TPU v4 lite'|device_kind == 'TPU v4 lite' or device_kind == 'TPU v5 lite'|g\" /usr/local/lib/python3.12/dist-packages/t5x/partitioning.py"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "1OI3L16olYQs"
      },
      "outputs": [],
      "source": [
        "# @title Run this cell to select backend and initialize model (~3 minutes)\n",
        "# @markdown For the open weights model, select **Magenta RT** as your backend and **leave your API key blank**.\n",
        "\n",
        "# @markdown For improved prompt coverage, we suggest using the [Lyria RealTime API](https://ai.google.dev/gemini-api/docs/music-generation); select **LyriaRT (API)** and paste your [Gemini API Key](https://ai.google.dev/gemini-api/docs/api-key).\n",
        "\n",
        "BACKEND = \"Magenta RT (Open weights)\" # @param [\"Magenta RT (Open weights)\", \"LyriaRT (API)\"]\n",
        "GEMINI_API_KEY = \"\" # @param {\"type\":\"string\", \"placeholder\": \"By default, you may leave this blank for the open weights model\"}\n",
        "\n",
        "if BACKEND.startswith(\"LyriaRT\"):\n",
        "  if len(GEMINI_API_KEY.strip()) == 0:\n",
        "    raise ValueError(\"You must input your Gemini API key\")\n",
        "  !pip install google-genai\n",
        "  from google import genai\n",
        "  from google.genai import types as genai_types\n",
        "  LRT = genai.Client(api_key=GEMINI_API_KEY, http_options={'api_version': 'v1alpha'})\n",
        "else:\n",
        "  from magenta_rt import system\n",
        "\n",
        "  # Fetch all assets from HuggingFace and initialize model (~5 minutes).\n",
        "  MRT = system.MagentaRT(tag=\"large\", lazy=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "00WPare9QS9O"
      },
      "source": [
        "# Step 2: 🤘 Streaming music generation! 🎵"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uWm6bVv1U2f2"
      },
      "source": [
        "**Run the cell below and click the `start` button to begin streaming!**\n",
        "\n",
        "**Instructions**. Type in text prompts to control the overall style of the\n",
        "generated music in real time. The sliders by the prompts change the influence of\n",
        "each text prompt on the overall output. The other controls change various\n",
        "aspects of the system behavior (expand below for additional information).\n",
        "\n",
        "**Disclaimer**. Magenta RT's training data primarily consists of Western\n",
        "instrumental music. As a consequence, Magenta RT has incomplete coverage of both\n",
        "vocal performance and the broader landscape of rich musical traditions\n",
        "worldwide. For real-time generation with broader style coverage, we suggest\n",
        "users select the **LyriaRT (API)** option in Step 1. See our\n",
        "[model card](https://huggingface.co/google/magenta-realtime) for more\n",
        "information.\n",
        "\n",
        "<details>\n",
        "  <summary>Click to expand for additional information on the controls</summary>\n",
        "\n",
        "*   **extra_buffering_seconds**: Increase this value if you experience audio\n",
        "    drops during generation. This will come at the expense of a greater latency,\n",
        "    but might help with internet connection issues. *You need to relaunch the\n",
        "    cell if you choose to modify this value*.\n",
        "\n",
        "*   **sampling options**\n",
        "\n",
        "    *   **temperature**: This controls how *chaotic* the model behaves. Low\n",
        "        temperature values (e.g., 0.9) will make the model's choices more\n",
        "        predictable and stable. High values (e.g., 1.5) will encourage more\n",
        "        surprising and experimental musical ideas, but can also lead to\n",
        "        instability.\n",
        "\n",
        "    *   **topk**: This parameter filters the model's vocabulary at each step. It\n",
        "        forces the model to choose its next prediction only from the *k* most\n",
        "        likely options.\n",
        "\n",
        "        *   A **low `topk`** value (e.g., 40) restricts the model to a smaller,\n",
        "            safer palette of options. This leads to more coherent and\n",
        "            predictable music that is less likely to have dissonant errors, but\n",
        "            can sometimes feel repetitive.\n",
        "        *   A **high `topk`** value gives the model a much wider range of\n",
        "            choices, allowing for more variety and unexpected turns. This can\n",
        "            make the output more creative, but also noisier.\n",
        "\n",
        "    *   **guidance**: This controls how strictly the generated music should\n",
        "        adhere to the **text prompts**.\n",
        "\n",
        "        *   A **higher value** will push the model to produce a textbook example\n",
        "            of the chosen style, emphasizing its key characteristics.\n",
        "        *   A **lower value** will treat the text prompts more as a loose\n",
        "            inspiration, allowing the model more creative freedom to deviate and\n",
        "            blend other influences.\n",
        "\n",
        "*   **Reset**: stop audio, and resets the model.\n",
        "\n",
        "*   **Text prompts**: Next to each text prompt is a slider that controls how\n",
        "    much each prompt should be affecting the model. This allows the creation of\n",
        "    *mixed* embeddings (try mixing synthwave and flamenco guitar together !).\n",
        "    You can also type your own prompt and modify existing ones.\n",
        "\n",
        "*   **Audio prompts**: Instead of using text to define a musical style, you can\n",
        "    also upload audio references! Click on the `Upload audio file` button to\n",
        "    create a new audio-based prompt. Note that only **the first 10s** of audio\n",
        "    will be used. Supported formats include `.wav`, `.mp3` and `.ogg`.\n",
        "\n",
        "</details>"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "4taDDhwf9hvD"
      },
      "outputs": [],
      "source": [
        "# @title Run this cell to start demo\n",
        "\n",
        "import abc\n",
        "import asyncio\n",
        "import concurrent.futures\n",
        "import functools\n",
        "import io\n",
        "import queue\n",
        "import threading\n",
        "import traceback\n",
        "from typing import Sequence\n",
        "\n",
        "import IPython.display as ipd\n",
        "import ipywidgets as ipw\n",
        "import numpy as np\n",
        "import soundfile as sf\n",
        "\n",
        "from magenta_rt import audio as audio_lib\n",
        "from magenta_rt import system\n",
        "from magenta_rt.colab import prompt_types\n",
        "from magenta_rt.colab import utils\n",
        "from magenta_rt.colab import widgets\n",
        "\n",
        "\n",
        "extra_buffering_seconds = 0  # @param {\"type\":\"slider\",\"min\":0,\"max\":4,\"step\":0.1}\n",
        "BUFFERING_AMOUNT_SAMPLES = int(np.ceil(extra_buffering_seconds * 48000))\n",
        "\n",
        "\n",
        "class AudioStreamer(abc.ABC):\n",
        "  \"\"\"Audio streamer base class.\"\"\"\n",
        "\n",
        "  def __init__(\n",
        "      self,\n",
        "      sample_rate: int = 48000,\n",
        "      num_channels: int = 2,\n",
        "      buffer_size: int = 48000 * 2,\n",
        "      extra_buffering: int = BUFFERING_AMOUNT_SAMPLES,\n",
        "  ):\n",
        "    self.audio_streamer = None\n",
        "    self.sample_rate = sample_rate\n",
        "    self.num_channels = num_channels\n",
        "    self.buffer_size = buffer_size\n",
        "    self.extra_buffering = extra_buffering\n",
        "\n",
        "  def on_stream_start(self):\n",
        "    \"\"\"Called when the UI starts streaming.\"\"\"\n",
        "    if self.audio_streamer is not None:\n",
        "      self.audio_streamer.reset_ring_buffer()\n",
        "\n",
        "  def on_stream_stop(self):\n",
        "    \"\"\"Called when the UI stops streaming.\"\"\"\n",
        "    pass\n",
        "\n",
        "  @property\n",
        "  @abc.abstractmethod\n",
        "  def warmup(self) -> bool:\n",
        "    \"\"\"Returns whether to warm up the audio streamer.\"\"\"\n",
        "    pass\n",
        "\n",
        "  def reset(self):\n",
        "    if self.audio_streamer is not None:\n",
        "      self.audio_streamer.reset_ring_buffer()\n",
        "\n",
        "  def start(self):\n",
        "    self.audio_streamer = utils.AudioStreamer(\n",
        "        self,\n",
        "        rate=self.sample_rate,\n",
        "        buffer_size=self.buffer_size,\n",
        "        warmup=self.warmup,\n",
        "        num_output_channels=self.num_channels,\n",
        "        additional_buffered_samples=self.extra_buffering,\n",
        "        start_streaming_callback=self.on_stream_start,\n",
        "        stop_streaming_callback=self.on_stream_stop,\n",
        "    )\n",
        "    self.reset()\n",
        "\n",
        "  def stop(self):\n",
        "    if self.audio_streamer is not None:\n",
        "      del self.audio_streamer\n",
        "      self.audio_streamer = None\n",
        "\n",
        "  def global_ui_params(self):\n",
        "    return utils.Parameters.get_values()\n",
        "\n",
        "  def get_prompts(self):\n",
        "    params = self.global_ui_params()\n",
        "    num_prompts = sum(map(lambda s: \"prompt_value\" in s, params.keys()))\n",
        "    prompts = []\n",
        "    for i in range(num_prompts):\n",
        "      prompt_weight = params[f\"prompt_weight_{i}\"]\n",
        "      prompt_value = params[f\"prompt_value_{i}\"]\n",
        "\n",
        "      if prompt_value is None or not prompt_weight:\n",
        "        continue\n",
        "\n",
        "      match type(prompt_value):\n",
        "        case prompt_types.TextPrompt:\n",
        "          prompt_value = prompt_value.strip()\n",
        "        case prompt_types.AudioPrompt:\n",
        "          pass\n",
        "        case prompt_types.EmbeddingPrompt:\n",
        "          pass\n",
        "        case _:\n",
        "          raise ValueError(f\"Unsupported prompt type: {type(prompt_value)}\")\n",
        "\n",
        "      prompts.append((prompt_value, prompt_weight))\n",
        "    return prompts\n",
        "\n",
        "  @abc.abstractmethod\n",
        "  def generate(self, ui_params):\n",
        "    pass\n",
        "\n",
        "  def __call__(self, inputs):\n",
        "    del inputs\n",
        "    return self.generate(self.global_ui_params())\n",
        "\n",
        "\n",
        "class MagentaRTStreamer(AudioStreamer):\n",
        "  \"\"\"Audio streamer class for our open weights Magenta RT model.\n",
        "\n",
        "  This class holds a pretrained Magenta RT model, a generation state and an\n",
        "  asynchronous executor to handle the embedding of text prompt without\n",
        "  interrupting the audio thread.\n",
        "\n",
        "  Args:\n",
        "    system: A MagentaRTBase instance.\n",
        "  \"\"\"\n",
        "\n",
        "  def __init__(self, system: system.MagentaRTBase):\n",
        "    super().__init__()\n",
        "    self.system = system\n",
        "    self.state = None\n",
        "    self.executor = concurrent.futures.ThreadPoolExecutor()\n",
        "\n",
        "  @property\n",
        "  def warmup(self):\n",
        "    return True\n",
        "\n",
        "  @functools.cache\n",
        "  def embed_style(self, style: str):\n",
        "    return self.executor.submit(self.system.embed_style, style)\n",
        "\n",
        "  @functools.cache\n",
        "  def embed_audio(self, audio: tuple[float]):\n",
        "    audio = audio_lib.Waveform(np.asarray(audio), 16000)\n",
        "    return self.executor.submit(self.system.embed_style, audio)\n",
        "\n",
        "  def get_style_embedding(self, force_wait: bool = False):\n",
        "    prompts = self.get_prompts()\n",
        "    weighted_embedding = np.zeros((768,), dtype=np.float32)\n",
        "    total_weight = 0.0\n",
        "    for prompt_value, prompt_weight in prompts:\n",
        "      match type(prompt_value):\n",
        "        case prompt_types.TextPrompt:\n",
        "          if not prompt_value:\n",
        "            continue\n",
        "          embedding = self.embed_style(prompt_value)\n",
        "\n",
        "        case prompt_types.AudioPrompt:\n",
        "          embedding = self.embed_audio(tuple(prompt_value.value))\n",
        "\n",
        "        case prompt_types.EmbeddingPrompt:\n",
        "          embedding = prompt_value.value\n",
        "\n",
        "        case _:\n",
        "          raise ValueError(f\"Unsupported prompt type: {type(prompt_value)}\")\n",
        "\n",
        "      if isinstance(embedding, concurrent.futures.Future):\n",
        "        if force_wait:\n",
        "          embedding.result()\n",
        "\n",
        "        if not embedding.done():\n",
        "          continue\n",
        "\n",
        "        embedding = embedding.result()\n",
        "\n",
        "      weighted_embedding += embedding * prompt_weight\n",
        "      total_weight += prompt_weight\n",
        "\n",
        "    if total_weight > 0:\n",
        "      weighted_embedding /= total_weight\n",
        "\n",
        "    return weighted_embedding\n",
        "\n",
        "  def on_stream_start(self):\n",
        "    self.get_style_embedding(force_wait=False)\n",
        "    self.get_style_embedding(force_wait=True)\n",
        "    super().on_stream_start()\n",
        "\n",
        "  def reset(self):\n",
        "    self.state = None\n",
        "    self.embed_style.cache_clear()\n",
        "    super().reset()\n",
        "\n",
        "  def generate(self, ui_params):\n",
        "    chunk, self.state = self.system.generate_chunk(\n",
        "        state=self.state,\n",
        "        style=self.get_style_embedding(),\n",
        "        seed=None,\n",
        "        **ui_params,\n",
        "    )\n",
        "    return chunk.samples\n",
        "\n",
        "  def stop(self):\n",
        "    self.executor.shutdown(wait=True)\n",
        "\n",
        "\n",
        "class LyriaRTStreamer(AudioStreamer):\n",
        "  \"\"\"Audio streamer for the asynchronous Lyria RealTime API.\n",
        "\n",
        "  This class bridges the synchronous `AudioStreamer` with the async `genai`\n",
        "  library by running the `asyncio` event loop in a dedicated background thread.\n",
        "  It uses thread-safe queues for communication.\n",
        "  \"\"\"\n",
        "\n",
        "  def __init__(self, client):  # Assuming client is genai.Client\n",
        "    super().__init__()\n",
        "    self.client = client\n",
        "    self.prompts = {}\n",
        "    self.params = {}\n",
        "    self.session = None\n",
        "    self.playback_state = \"stopped\"\n",
        "    # Queues for thread-safe communication\n",
        "    self.audio_queue = queue.Queue(maxsize=10)  # Buffer a few chunks\n",
        "    self.update_queue = queue.Queue(maxsize=1)\n",
        "\n",
        "    # Background thread management\n",
        "    self._thread: threading.Thread | None = None\n",
        "    self._stop_event = threading.Event()\n",
        "\n",
        "  def start(self):\n",
        "    \"\"\"Starts the background thread for the asyncio event loop.\"\"\"\n",
        "    if self._thread is None:\n",
        "      self._stop_event.clear()\n",
        "      self._thread = threading.Thread(target=self._run_async_loop, daemon=True)\n",
        "      self._thread.start()\n",
        "    super().start()\n",
        "\n",
        "  def stop(self):\n",
        "    \"\"\"Signals the background thread to stop and waits for it to exit.\"\"\"\n",
        "    if self._thread and self._thread.is_alive():\n",
        "      self._stop_event.set()\n",
        "      self._thread.join(timeout=5)\n",
        "    self._thread = None\n",
        "    super().stop()\n",
        "\n",
        "  @property\n",
        "  def warmup(self):\n",
        "    # Wait for the user starts the stream before requesting the first audio chunk.\n",
        "    return False\n",
        "\n",
        "  def on_stream_start(self):\n",
        "    if self.session is not None:\n",
        "      asyncio.run(self.session.play())\n",
        "      self.playback_state = \"playing\"\n",
        "      super().on_stream_start()\n",
        "\n",
        "  def on_stream_stop(self):\n",
        "    if self.session is not None:\n",
        "      asyncio.run(self.session.stop())\n",
        "      self.playback_state = \"stopped\"\n",
        "      self.reset()  # Drain the audio queue\n",
        "      super().on_stream_stop()\n",
        "\n",
        "  def _run_async_loop(self):\n",
        "    \"\"\"The target method for the background thread.\"\"\"\n",
        "    try:\n",
        "      asyncio.run(self._manage_session())\n",
        "    except Exception as e:\n",
        "      print(f\"Error in async loop: {e}\")\n",
        "\n",
        "  async def _manage_session(self):\n",
        "    \"\"\"Main async task to connect to Lyria RealTime API and handle communication.\"\"\"\n",
        "    from google.genai import types as genai_types  # Late import for clarity\n",
        "\n",
        "    while not self._stop_event.is_set():\n",
        "      try:\n",
        "        # Establish a connection\n",
        "        async with self.client.aio.live.music.connect(\n",
        "            model=\"models/lyria-realtime-exp\"\n",
        "        ) as session:\n",
        "          self.session = session\n",
        "          # Start a background task to continuously receive audio\n",
        "          receive_task = asyncio.create_task(self._receive_audio(session))\n",
        "\n",
        "          # Wait for the first set of parameters to arrive\n",
        "          initial_params = await self._get_next_update(None)\n",
        "          if initial_params:\n",
        "            await self._apply_params(session, initial_params, genai_types)\n",
        "\n",
        "          if self.playback_state == \"playing\":\n",
        "            # Resume playback on automatic reconnection.\n",
        "            await session.play()\n",
        "\n",
        "          # Main loop to process parameter updates\n",
        "          while not self._stop_event.is_set() and not receive_task.done():\n",
        "            latest_params = await self._get_next_update(timeout=0.1)\n",
        "            if latest_params:\n",
        "              await self._apply_params(session, latest_params, genai_types)\n",
        "\n",
        "          # Reset session parameters so they are set on the next connection.\n",
        "          self.prompts = {}\n",
        "          self.params = {}\n",
        "          receive_task.cancel()\n",
        "          await asyncio.gather(receive_task, return_exceptions=True)\n",
        "\n",
        "      except Exception as e:\n",
        "        traceback.print_exc()\n",
        "        print(f\"Lyria RealTime session failed, will retry in 5s: {e}\")\n",
        "        if self._stop_event.is_set():\n",
        "          break\n",
        "        await asyncio.sleep(5)\n",
        "\n",
        "      self.session = None  # The session has been closed at this point.\n",
        "\n",
        "  async def _get_next_update(self, timeout=None):\n",
        "    \"\"\"Asynchronously waits for the next item in the update queue.\"\"\"\n",
        "    loop = asyncio.get_running_loop()\n",
        "    try:\n",
        "      # Use a future to bridge the sync queue with the async loop\n",
        "      return await loop.run_in_executor(\n",
        "          None, lambda: self.update_queue.get(timeout=timeout)\n",
        "      )\n",
        "    except queue.Empty:\n",
        "      return None\n",
        "\n",
        "  async def _apply_params(self, session, ui_params, genai_types):\n",
        "    \"\"\"Applies UI parameters to the live session.\"\"\"\n",
        "    prompts = self.get_prompts()\n",
        "    params = {\n",
        "        \"temperature\": ui_params.get(\"temperature\"),\n",
        "        \"top_k\": ui_params.get(\"topk\"),\n",
        "        \"guidance\": ui_params.get(\"guidance_weight\"),\n",
        "    }\n",
        "    if prompts != self.prompts:\n",
        "      self.prompts = prompts\n",
        "      norm = sum(w for _, w in prompts) or 1.0\n",
        "      await session.set_weighted_prompts(\n",
        "          prompts=[\n",
        "              genai_types.WeightedPrompt(text=p, weight=w / norm)\n",
        "              for p, w in prompts\n",
        "          ]\n",
        "      )\n",
        "    if params != self.params:\n",
        "      self.params = params\n",
        "      await session.set_music_generation_config(\n",
        "          config=genai_types.LiveMusicGenerationConfig(\n",
        "              temperature=params.get(\"temperature\"),\n",
        "              top_k=params.get(\"topk\"),\n",
        "              guidance=params.get(\"guidance_weight\"),\n",
        "          )\n",
        "      )\n",
        "\n",
        "  async def _receive_audio(self, session):\n",
        "    \"\"\"Task to receive audio chunks from the server and queue them.\"\"\"\n",
        "    async for message in session.receive():\n",
        "      if message.server_content and message.server_content.audio_chunks:\n",
        "        audio_data = message.server_content.audio_chunks[0].data\n",
        "        try:\n",
        "          # Extract interleaved stereo channels.\n",
        "          stereo_samples = np.frombuffer(audio_data, dtype=np.int16).reshape(\n",
        "              -1, 2\n",
        "          )\n",
        "          # Write samples to an in memory wav file to read them back as bytes.\n",
        "          buffer = io.BytesIO()\n",
        "          sf.write(buffer, stereo_samples, self.sample_rate, format=\"WAV\")\n",
        "          buffer.seek(0)\n",
        "          samples, _ = sf.read(buffer)\n",
        "          self.audio_queue.put(samples)\n",
        "        except Exception as e:\n",
        "          print(f\"Error reading audio data: {e}\")\n",
        "          traceback.print_exc()\n",
        "          raise e\n",
        "\n",
        "  def reset(self):\n",
        "    \"\"\"Clears queues and primes the update queue with current params.\"\"\"\n",
        "    # Clear any stale data from queues\n",
        "    while not self.audio_queue.empty():\n",
        "      try:\n",
        "        self.audio_queue.get_nowait()\n",
        "      except queue.Empty:\n",
        "        break\n",
        "    while not self.update_queue.empty():\n",
        "      try:\n",
        "        self.update_queue.get_nowait()\n",
        "      except queue.Empty:\n",
        "        break\n",
        "\n",
        "    # Prime the queue with the initial parameters to break the deadlock.\n",
        "    self.update_queue.put_nowait(self.global_ui_params())\n",
        "\n",
        "    # Call the base class reset.\n",
        "    super().reset()\n",
        "\n",
        "  def generate(self, ui_params):\n",
        "    \"\"\"(Synchronous) Provides audio to the streamer.\n",
        "\n",
        "    Sends new params to the async loop and gets the next available audio chunk.\n",
        "    \"\"\"\n",
        "    # Try to send the latest params to the async loop.\n",
        "    # If the queue is full, the last update is just replaced.\n",
        "    if self.update_queue.full():\n",
        "      try:\n",
        "        self.update_queue.get_nowait()  # Discard old update\n",
        "      except queue.Empty:\n",
        "        pass  # Race condition, another thread got it. Fine.\n",
        "    self.update_queue.put_nowait(ui_params)\n",
        "\n",
        "    # Block and wait for the next audio chunk from the async loop.\n",
        "    try:\n",
        "      return self.audio_queue.get(timeout=5)\n",
        "    except queue.Empty:\n",
        "      print(\"Audio queue timeout. Returning silence.\")\n",
        "      # Return silence matching the expected format if no audio is available\n",
        "      return np.zeros(\n",
        "          (self.sample_rate * 2, self.num_channels), dtype=np.float32\n",
        "      ).tobytes()\n",
        "\n",
        "  def __del__(self):\n",
        "    self.stop()\n",
        "\n",
        "\n",
        "# BUILD UI\n",
        "\n",
        "\n",
        "def build_prompt_ui(default_prompts: Sequence[str], num_audio_prompt: int):\n",
        "  \"\"\"Add interactive prompt widgets and register them.\"\"\"\n",
        "  prompts = []\n",
        "\n",
        "  for p in default_prompts:\n",
        "    prompts.append(widgets.Prompt())\n",
        "    prompts[-1].text.value = p\n",
        "\n",
        "  prompts[0].slider.value = 1.0\n",
        "\n",
        "  # add audio prompt\n",
        "  for _ in range(num_audio_prompt):\n",
        "    prompts.append(widgets.AudioPrompt())\n",
        "    prompts[-1].slider.value = 0.0\n",
        "\n",
        "  utils.Parameters.register_ui_elements(\n",
        "      display=False,\n",
        "      **{f\"prompt_weight_{i}\": p.slider for i, p in enumerate(prompts)},\n",
        "      **{f\"prompt_value_{i}\": p.prompt_value for i, p in enumerate(prompts)},\n",
        "  )\n",
        "  return [p.get_widget() for p in prompts]\n",
        "\n",
        "\n",
        "def build_sampling_option_ui():\n",
        "  \"\"\"Add interactive sampling option widgets and register them.\"\"\"\n",
        "  options = {\n",
        "      \"temperature\": ipw.FloatSlider(\n",
        "          min=0.0,\n",
        "          max=4.0,\n",
        "          step=0.01,\n",
        "          value=1.3,\n",
        "          description=\"temperature\",\n",
        "      ),\n",
        "      \"topk\": ipw.IntSlider(\n",
        "          min=0,\n",
        "          max=1024,\n",
        "          step=1,\n",
        "          value=40,\n",
        "          description=\"topk\",\n",
        "      ),\n",
        "      \"guidance_weight\": ipw.FloatSlider(\n",
        "          min=0.0,\n",
        "          max=10.0,\n",
        "          step=0.01,\n",
        "          value=5.0,\n",
        "          description=\"guidance\",\n",
        "      ),\n",
        "  }\n",
        "\n",
        "  utils.Parameters.register_ui_elements(display=False, **options)\n",
        "\n",
        "  return list(options.values())\n",
        "\n",
        "\n",
        "utils.Parameters.reset()\n",
        "\n",
        "\n",
        "# Make sure setup cell was run\n",
        "try:\n",
        "  BACKEND\n",
        "except NameError:\n",
        "  raise RuntimeError(\"Please run the cell above.\")\n",
        "\n",
        "\n",
        "# Initialize streamer\n",
        "if BACKEND.startswith(\"LyriaRT\"):\n",
        "  try:\n",
        "    LRT\n",
        "  except NameError:\n",
        "    raise RuntimeError(\"Please run the cell above.\")\n",
        "  streamer = LyriaRTStreamer(LRT)\n",
        "else:\n",
        "  try:\n",
        "    MRT\n",
        "  except NameError:\n",
        "    raise RuntimeError(\"Please run the cell above.\")\n",
        "  streamer = MagentaRTStreamer(MRT)\n",
        "\n",
        "\n",
        "def _reset_state(*args, **kwargs):\n",
        "  del args, kwargs\n",
        "  streamer.reset()\n",
        "\n",
        "\n",
        "reset_button = ipw.Button(description=\"reset\")\n",
        "reset_button.on_click(_reset_state)\n",
        "\n",
        "\n",
        "# Building interactive UI\n",
        "ipd.display(\n",
        "    ipw.VBox([\n",
        "        widgets.area(\n",
        "            \"sampling options\",\n",
        "            *build_sampling_option_ui(),\n",
        "            reset_button,\n",
        "        ),\n",
        "        widgets.area(\n",
        "            \"prompts\",\n",
        "            *build_prompt_ui(\n",
        "                [\n",
        "                    \"synthwave\",\n",
        "                    \"flamenco guitar\",\n",
        "                    \"\",\n",
        "                    \"\",\n",
        "                ],\n",
        "                num_audio_prompt=0 if BACKEND.startswith(\"LyriaRT\") else 2,\n",
        "            ),\n",
        "        ),\n",
        "    ])\n",
        ")\n",
        "\n",
        "streamer.start()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RPJxjMnOqIU-"
      },
      "source": [
        "# Step 3: Understand what is happening behind the hood"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x_8cVQiQ34v9"
      },
      "source": [
        "Let's start by generating a short (2s) chunk of synthwave"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BTzfxJ1fqQAF"
      },
      "outputs": [],
      "source": [
        "import IPython.display as ipd\n",
        "\n",
        "try:\n",
        "  model = MRT\n",
        "except NameError:\n",
        "  model = system.MagentaRT(tag=\"large\", device=\"tpu:v2-8\", lazy=False)\n",
        "\n",
        "prompt = \"synthwave\"\n",
        "embedding = model.embed_style(prompt)\n",
        "\n",
        "audio, state = model.generate_chunk(\n",
        "    state=None,\n",
        "    style=embedding,\n",
        "    seed=0,\n",
        ")\n",
        "\n",
        "ipd.display(ipd.Audio(audio.samples.T, rate=audio.sample_rate))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fGHSTwpCrsJx"
      },
      "source": [
        "We can generate longer sequences by concatenating generations while keeping\n",
        "track of the internal state of the model. We use a crossfade time of 40ms to\n",
        "concatenate audio chunks as this is the frame length used by SpectroStream when\n",
        "encoding audio."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "M2FDcW9prrWu"
      },
      "outputs": [],
      "source": [
        "from magenta_rt import audio\n",
        "\n",
        "num_chunks = 4\n",
        "state = None\n",
        "chunks = []\n",
        "\n",
        "for i in range(num_chunks):\n",
        "  chunk, state = model.generate_chunk(\n",
        "      state=state,\n",
        "      style=embedding,\n",
        "      seed=i,\n",
        "  )\n",
        "  chunks.append(chunk)\n",
        "\n",
        "concatenated_audio = audio.concatenate(chunks)\n",
        "ipd.display(\n",
        "    ipd.Audio(concatenated_audio.samples.T, rate=concatenated_audio.sample_rate)\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mKGsDvChsrr4"
      },
      "source": [
        "At the core of Magenta RT lies the idea of changing the style embedding *during\n",
        "generation* to enable smooth transitions between musical concepts. What about\n",
        "transitioning from \"synthwave\" to \"disco funk\" ?"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Zx_bEjtcs6yB"
      },
      "outputs": [],
      "source": [
        "state = None\n",
        "chunks = []\n",
        "\n",
        "styles = [\n",
        "    \"synthwave\",\n",
        "    \"disco synthwave\",\n",
        "    \"disco\",\n",
        "    \"disco funk\",\n",
        "]\n",
        "\n",
        "for i, style in enumerate(styles):\n",
        "  chunk, state = model.generate_chunk(\n",
        "      state=state,\n",
        "      style=model.embed_style(style),\n",
        "      seed=i,\n",
        "      guidance_weight=5.0,\n",
        "      temperature=1.3,\n",
        "  )\n",
        "  chunks.append(chunk)\n",
        "\n",
        "concatenated_audio = audio.concatenate(chunks)\n",
        "ipd.display(\n",
        "    ipd.Audio(concatenated_audio.samples.T, rate=concatenated_audio.sample_rate)\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-iiqJYDYxasB"
      },
      "source": [
        "A simpler version can be done through the interpolation of musical genres in\n",
        "*the embedding space*."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "n8Etm7CtxaRu"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "state = None\n",
        "chunks = []\n",
        "\n",
        "embed_a = model.embed_style(\"synthwave\")\n",
        "embed_b = model.embed_style(\"disco funk\")\n",
        "\n",
        "weight = np.linspace(0, 1, 8, endpoint=True)\n",
        "\n",
        "embeddings = embed_a[None] + weight[:, None] * (embed_b - embed_a)\n",
        "embeddings = embeddings.astype(np.float32)\n",
        "\n",
        "\n",
        "for i, embedding in enumerate(embeddings):\n",
        "  chunk, state = model.generate_chunk(\n",
        "      state=state,\n",
        "      style=embedding,\n",
        "      seed=i,\n",
        "      guidance_weight=5.0,\n",
        "      temperature=1.3,\n",
        "  )\n",
        "  chunks.append(chunk)\n",
        "\n",
        "concatenated_audio = audio.concatenate(chunks)\n",
        "ipd.display(\n",
        "    ipd.Audio(concatenated_audio.samples.T, rate=concatenated_audio.sample_rate)\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xmvBk8UOphdL"
      },
      "source": [
        "# License and terms\n",
        "\n",
        "Magenta RealTime is offered under a combination of licenses: the codebase is\n",
        "licensed under\n",
        "[Apache 2.0](https://github.com/magenta/magenta-realtime/blob/main/LICENSE), and\n",
        "the model weights under\n",
        "[Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode).\n",
        "\n",
        "In addition, we specify the following usage terms:\n",
        "\n",
        "Copyright 2025 Google LLC\n",
        "\n",
        "Use these materials responsibly and do not generate content, including outputs,\n",
        "that infringe or violate the rights of others, including rights in copyrighted\n",
        "content.\n",
        "\n",
        "Google claims no rights in outputs you generate using Magenta RealTime. You and\n",
        "your users are solely responsible for outputs and their subsequent uses.\n",
        "\n",
        "Unless required by applicable law or agreed to in writing, all software and\n",
        "materials distributed here under the Apache 2.0 or CC-BY licenses are\n",
        "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n",
        "either express or implied. See the licenses for the specific language governing\n",
        "permissions and limitations under those licenses. You are solely responsible for\n",
        "determining the appropriateness of using, reproducing, modifying, performing,\n",
        "displaying or distributing the software and materials, and any outputs, and\n",
        "assume any and all risks associated with your use or distribution of any of the\n",
        "software and materials, and any outputs, and your exercise of rights and\n",
        "permissions under the licenses."
      ]
    }
  ],
  "metadata": {
    "accelerator": "TPU",
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
